﻿using System;
using System.Net;

namespace Firefly.ExtensionMethods
{
    public static class IPAddressExtensions
    {
        public static byte[] ToNetworkOrderByteArray(this IPAddress obj)
        {
            if (obj != IPAddress.None && obj != null)
            {
                byte[] hoa = obj.GetAddressBytes();
                ulong longIp = (ulong)((hoa[0] << 24) |
                    (hoa[1] << 16) |
                    (hoa[2] << 8) |
                    hoa[3]);
                ulong no = (ulong)IPAddress.HostToNetworkOrder((long)longIp);
                byte[] noa = BitConverter.GetBytes(no);
                byte[] ipa = new byte[4];
                ipa[0] = noa[7];
                ipa[1] = noa[6];
                ipa[2] = noa[5];
                ipa[3] = noa[4];
                return ipa;
            }

            return null;
        }

        public static byte[] ToHostOrderByteArray(this IPAddress obj)
        {
            if (obj != IPAddress.None && obj != null)
            {
                byte[] hoa = obj.GetAddressBytes();
                return hoa;
            }

            return null;
        }
    }
}